package com.file;

import com.utils.FileUtil;
import sun.misc.BASE64Encoder;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

@WebServlet(name = "DownloadFile", urlPatterns = {"/DownloadFile"})
public class DownloadFile extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String filename = new String(req.getParameter("filename"));
        // 2.1设置Content-Type头
        String type = this.getServletContext().getMimeType(filename);
        resp.setHeader("Content-Type", type);
        String realPath = FileUtil.BASE_PATH + File.separator + filename;
        // 根据浏览器的类型处理中文文件的乱码问题:
        String agent = req.getHeader("User-Agent");
        if (agent.contains("Firefox")) {
            filename = base64EncodeFileName(filename);
        } else {
            filename = URLEncoder.encode(filename, "UTF-8");
        }
        // 2.2设置Content-Disposition头
        resp.setHeader("Content-Disposition", "attachment;filename=" + filename);
        InputStream is = new FileInputStream(realPath);
        // 获得response的输出流:
        OutputStream os = resp.getOutputStream();
        int len = 0;
        byte[] chs = new byte[1024];
        while ((len = is.read(chs)) != -1) {
            os.write(chs, 0, len);
        }
        is.close();
    }

    public static String base64EncodeFileName(String fileName) {
        BASE64Encoder base64Encoder = new BASE64Encoder();
        try {
            return "=?UTF-8?B?" + new String(base64Encoder.encode(fileName.getBytes("UTF-8"))) + "?=";
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

}
